package com.niuke;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * 64. 周末爬山
 * https://blog.csdn.net/m0_46181452/article/details/131914816
 */
public class NiukeMoni64 {

    public static int[][] offsets = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String[] line1 = scanner.nextLine().split(" ");
        int row = Integer.parseInt(line1[0]);
        int col = Integer.parseInt(line1[1]);
        int k = Integer.parseInt(line1[2]); // 上山或下山不能超过的高度
        int[][] data = new int[row][col];

        for (int i = 0; i < row; i++) {
            String[] line = scanner.nextLine().split(" ");
            int[] item = new int[line.length];
            for (int j = 0; j < line.length; j++) {
                item[j] = Integer.parseInt(line[j]);
            }
            data[i] = item;
        }

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});

        // 记录最佳答案
        int[] ans = new int[2];
        ans[0] = data[0][0];

        // 记步数
        int[][] dp = new int[row][col];

        while (queue.size() > 0) {
            int[] currPosition = queue.poll();
            int x = currPosition[0];
            int y = currPosition[1];
            int currHeight = data[x][y];
            if (currHeight > ans[0]) {
                ans[0] = currHeight;
                ans[1] = dp[x][y];
                System.out.println(ans[0] + "---" + ans[1]);
            }

            for (int i = 0; i < offsets.length; i++) {
                int[] offset = offsets[i];
                int xx = x + offset[0];
                int yy = y + offset[1];
                if (xx >= 0 && xx < row && yy >= 0 && yy < col) {
                    int nextHeight = data[xx][yy];
                    if (nextHeight != -1 && Math.abs(nextHeight - currHeight) <= k) {
                        dp[xx][yy] = dp[x][y] + 1;
                        queue.offer(new int[]{xx, yy});
                    }
                }
            }

            // 走过的不再能走，置为-1作为标识
            data[x][y] = -1;
        }

        System.out.println("最高峰 = " + ans[0] + ", 步数 = " + ans[1]);

        for (int j = 0; j < dp.length; j++) {
            System.out.println(Arrays.toString(dp[j]));
        }
    }

}
